unit dbcTableDataComparer;
// Database Comparer VCL v.3.0
// Copyright (C) 1998-2006, by Boris Loboda
// www.CleverComponents.com
{$I Comparer.INC}

// 20.02.2005 (BL)
// - Compare table data.
// 15.03.2005 (BL)
// - Blob-fields compare. Save result script & Blobs-file (*.LOB).
//   Properties: ScriptFileName, BlobFileName added.
// 18.03.2005 (BL)
// - Properties: SQLExec, ExcludeFields added.
// 23.07.2005
// - Compare tables with difference fields (TableOptionsMaster, TableOptionsTarget).
// - Output data formatting (FloatFormat, DateFormat, TimeFormat, DateTimeFormat).
// - Compare MySQL, MS SQL tables.
// 04.08.2005
// - Compare local tables (Paradox, dBASE).
// - MySQL QuotedStr(...) fix.
// 04.10.2005
// - Extract data from one MasterTable, if TargetTable (DBCConnectionTarget)
//   is not specified.
// 11.10.2005
// - OnGetDataValue event implemented.
// 13.12.2005
// - Sybase (ASA) support added.
// 21.01.2006
// - Oracle support added.
// 27.02.2006
// - IngnoreComputedFields property.
// 05.03.2006
// - Output format fix for float values.
// 05.03.2007
// - OLEDB support added.
// 24.12.2007
// - IB/FB: Quoted identifiers fix.
// 05.09.2013
// ANSI/Unicode result script

interface

Uses SysUtils, Classes, Contnrs, DB,
     dbcSQL_Exec,
     {$IFDEF Delphi6} Variants,{$ENDIF}
     dbcTypes, dbcClasses, dbcMsgMngr,
     dbcDBOptions,
     dbcIBSQLExec,
     dbcDBEngine;

type
  TTableDataComparer = class;

  TCmpTableOptions = class(TPersistent)
  private
    // internal
    fFlds: TStrings;        // table fields (all existing)
    dFlds, kFlds, eFlds: TStrings; // internal data/key/exclude fields
    fBlobFlds: TStrings;
    fPk: TStrings;
    fUnique: TStrings;
    // properties
    fTableName: String;
    fKeyFlds: TStrings;     // key fields
    fDataFlds: TStrings;    // data fields to copy record
    fExclFlds: TStrings;    // exclude data fields
                            // (if fDataFlds is impty, fDataFields := fFlds - fExclFlds)
    fOwner: TTableDataComparer;
    fConnection: TDBCCustomConnection;
    fAllowSystemTables: Boolean;
  protected
    procedure AssignTo(Dest: TPersistent); override;
    function FldsSeq(aFlds: TStrings): String;
    function QuoteField(aIdent: String): String;
    function FldValue(const aValue: Variant): String; overload;
    function FldValue(const Fld: TField): String; overload;
    function FldsSeqValue(Q: TDBCQuery): String;
    function PrepareFields(Q: TDBCQuery): Boolean;
    procedure SetKeyFlds(aFlds: TStrings);
    procedure SetDataFlds(aFlds: TStrings);
    procedure SetExclFlds(aFlds: TStrings);
    function GetDBFields(Q: TDBCQuery): Boolean;
    function SelectSQL(): String;
  public
    constructor Create (aOwner: TComponent);
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
    procedure Clear;
    property TableName: string read fTableName;
    function QuoteIdent(aIdent: String): String;
  published
    property KeyFields: TStrings read fKeyFlds write SetKeyFlds;
    property DataFields: TStrings read fDataFlds write SetDataFlds;
    property ExcludeFields: TStrings read fExclFlds write SetExclFlds;
    property AllowSystemTables: Boolean read fAllowSystemTables
                                        write fAllowSystemTables
                                        default False; 
  end;

  TDataCompareOperation = (dcopInsert, dcopUpdate, dcopDelete);
  TDataCompareOperations = Set of TDataCompareOperation;

  TCompareFieldsEvent = function (Sender: TObject; FieldM, FieldT: TField): integer of object;
  TGetFieldsEvent     = procedure (Sender: TObject; const FieldsM, FieldsT: TStrings) of object;
  TGetSQLEvent        = procedure (Sender: TObject; const SQLM, SQLT: TStrings) of object;
  TGetDataValueEvent  = procedure (Sender: TObject; const Field: TField; var aValue: String) of object;
  TAddResultSQLEvent  = procedure (Sender: TObject;
                                   var Accept: Boolean;
                                   aSQL: String;
                                   aStatType: TStatType;
                                   aObjName: string;
                                   aObjType: TDBObject;
                                   opType: TDbOperation) of object;

  TTableDataComparer = class(TComponent)
  protected
    fOnLogNextLine: TLogNextLineEvent;
    fOnErrorMessage: TErrorMessageEvent;
    // Query component - read data from master/target
    fQM, fQT: TDBCQuery;
    // update query (UpdateImmediately = True)
    fQU: TDBCQuery;
    fProgressMaster: TProgressUpdateEvent;
    fProgressTarget: TProgressUpdateEvent;
    fMRecCnt, fTRecCnt: integer;
    fMRecCur, fTRecCur: integer;
    fCustomKeyFields: TStrings;
    fCustomDataFields: TStrings;
    fExcludeFields: TStrings;
    fUpdateRecord: Boolean;
    fAllowedOperations: TDataCompareOperations;
    fUpdateImmediately: Boolean;
    fCompareBlobs: Boolean;
    fIncludeBlobs: Boolean;
    fScriptFileName: TFileName;
    fScriptStream: TFileStream;
    fBlobFileName: TFileName;
    fBlobStream: TFileStream;
    fBlobFileError: Boolean;
    fBlobFieldExists: Boolean;
    fSQLExec: TCustomSQLExec;
    fMsgMngr: TMsgManager;
    fConnectionOptions: TConnectionOptions;
    fIBServerOptions: TIBTableDataComparerOptions;
    fMSSQLServerOptions: TMSSQLServerOptions;
    fMySQLServerOptions: TMySQLServerOptions;
    fConnectionMaster: TDBCCustomConnection;
    fConnectionTarget: TDBCCustomConnection;
    fScriptOptions: TScriptOptions;
    fCompareFields: TCompareFieldsEvent;
    fGetKeyFields: TGetFieldsEvent;
    fGetDataFields: TGetFieldsEvent;
    fGetExcludeFields: TGetFieldsEvent;
    fGetDataValue: TGetDataValueEvent;
    fTableOptionsM: TCmpTableOptions;
    fTableOptionsT: TCmpTableOptions;
    fGetSelectSQL: TGetSQLEvent;
    fGetCountSQL: TGetSQLEvent;
    ConnectionMasterActive: Boolean;
    ConnectionTargetActive: Boolean;
    fTblNameM, fTblNameT: String;
    fTrimCharFields: Boolean;
    fRecInserted: Integer;
    fRecUpdated: Integer;
    fRecDeleted: Integer;
    fRecEqual: Integer;
    fErrors: Integer;
    fAddResultSQL: TAddResultSQLEvent;
    fBeforeOpen: TDataSetNotifyEvent;
    fIgnoreComputedFields: Boolean;
{$ifdef Delphi2009}
    fEncode: TdbcEncode;
{$endif}
    procedure DoProgressMaster();
    procedure DoProgressTarget();
    // compare data
    procedure Compare();
    // set properties for Transaction & Query Components
    procedure CompareTableData();
    function WhereSeq(Q: TDBCQuery; fKeyFields: TStrings): String;
    function CompareFields(FldM, FldT: Tfield): integer;
    function CompareRecord(): integer;
    procedure RecordInsert();
    procedure RecordUpdate();
    procedure RecordDelete();
    procedure MakeConnectString();
    procedure SetScriptFileName(const aFileName: TFileName);
    function CompareBlobFields(FldM, FldT: TField): Integer;
    procedure SetConnectionMaster(aConnection: TDBCCustomConnection);
    procedure SetConnectionTarget(aConnection: TDBCCustomConnection);
    procedure SetSQLExec(aSQLExec: TCustomSQLExec);
    procedure Notification(AComponent: TComponent;
      Operation: TOperation); override;
    procedure DoAddResultSQL(aSQL: String;
                             aStatType: TStatType;
                             aObjName: string = '';
                             aObjType: TDBObject = dboUnknown;
                             opType: TDbOperation = odbUnknown);
    procedure SetScriptOptions(aOptions: TScriptOptions);
    procedure SetTableOptionsM(aOptions: TCmpTableOptions);
    procedure SetTableOptionsT(aOptions: TCmpTableOptions);
    function GetPkFldsCount(): Integer;
    function GetUniqueFldsCount(): Integer;
    function GetKeyFldsCount(): Integer;
    function GetDataFldsCount(): Integer;
    property PkFldsCount: integer read GetPkFldsCount;
    property UniqueFldsCount: integer read GetUniqueFldsCount;
    property KeyFldsCount: integer read GetKeyFldsCount;
    function SaveBlob(Fld: TField): String;
    procedure SetTableNameMaster(aTableName: String);
    procedure SetTableNameTarget(aTableName: String);
    function GetTableNameMaster(): String;
    function GetTableNameTarget(): String;
    procedure SetCustomKeyFields(aFlds: TStrings);
    procedure SetCustomDataFields(aFlds: TStrings);
    procedure SetExcludeFields(aFlds: TStrings);
    procedure DoGetSelectSQL(fMSQL, fTSQL: TStrings);
    function GetDatabaseType(): TDatabaseType;
    procedure SetUpdateImmediately(aValue: Boolean);
  public
    constructor Create(aOwner: TComponent); override;
    destructor Destroy; override;
    // compare data tables and generate result script
    function CompareData(): Boolean;
    procedure DoLogNextLine(LogLine: String);
    procedure DoErrMsg(aMsg: String);
    procedure DoWrnMsg(aMsg: String);
    property ConnectionOptions: TConnectionOptions read fConnectionoptions;
    property IBserverOptions: TIBTableDataComparerOptions read fIBServerOptions;
    property MSSQLServerOptions: TMSSQLServeroptions read fMSSQLServerOptions;
    property MySQLServerOptions: TMySQLServeroptions read fMySQLServerOptions;
    property DatabaseType : TDatabaseType read GetDatabaseType;
    property RecInserted: integer read fRecInserted;
    property RecDeleted: integer read fRecDeleted;
    property RecUpdated: integer read fRecUpdated;
    property RecEqual: integer read fRecEqual;
    property Errors: Integer read fErrors;
  published
    property TableNameMaster: string
      read GetTableNameMaster write SetTableNameMaster;
    property TableNameTarget: string
      read GetTableNameTarget write SetTableNameTarget;
    property UpdateImmediately: Boolean read fUpdateImmediately
                                        write SetUpdateImmediately
                                        default False;
    property CompareBlobs: Boolean read fCompareBlobs
                                   write fCompareBlobs
                                   default True;
    property IncludeBlobs: Boolean read fIncludeBlobs
                                   write fIncludeBlobs
                                   default True;
    property DBCConnectionMaster: TDBCCustomConnection read  fConnectionMaster
                                write SetConnectionMaster;
    property DBCConnectionTarget: TDBCCustomConnection read  fConnectionTarget
                                write SetConnectionTarget;
    property TableOptionsMaster: TCmpTableOptions
      read fTableOptionsM write SetTableOptionsM;
    property TableOptionsTarget: TCmpTableOptions
      read fTableOptionsT write SetTableOptionsT;
    property CustomKeyFields: TStrings read fCustomKeyFields
                                     write SetCustomKeyFields;
    property CustomDataFields: TStrings read fCustomDataFields
                                     write SetCustomDataFields;
    property AllowedOperations: TDataCompareOperations
                                read fAllowedOperations
                                write fAllowedOperations
                                default [dcopInsert, dcopUpdate, dcopDelete];
    property ScriptOptions: TScriptOptions read fScriptOptions write SetScriptOptions;
    // Result script
    property ScriptFileName: TFileName read fScriptFileName write SetScriptFileName;
    // Result BLOBs
    property BlobFileName: TFileName read fBlobFileName write fBlobFileName;
    property SQLExec: TCustomSQLExec read fSQLExec write SetSQLExec;
    property ExcludeDataFields: TStrings read fExcludeFields write SetExcludeFields;
    property TrimCharFields: Boolean read fTrimCharFields write fTrimCharFields default False;
    property IgnoreComputedFields: Boolean read fIgnoreComputedFields
                                           write fIgnoreComputedFields
                                           default True; 
    property OnLogNextLine: TLogNextLineEvent
      read fOnLogNextLine write fOnLogNextLine;
    property OnErrorMessage: TErrorMessageEvent
      read fOnErrorMessage write fOnErrorMessage;
    property OnProgressUpdateMaster: TProgressUpdateEvent
      read fProgressMaster write fProgressMaster;
    property OnProgressUpdateTarget: TProgressUpdateEvent
      read fProgressTarget write fProgressTarget;
    property OnCompareFields: TCompareFieldsEvent
      read fCompareFields write fCompareFields;
    property OnGetKeyFields: TGetFieldsEvent
      read fGetKeyFields write fGetKeyFields;
    property OnGetDataFields: TGetFieldsEvent
      read fGetDataFields write fGetDataFields;
    property OnGetExcludeFields: TGetFieldsEvent
      read fGetExcludeFields write fGetExcludeFields;
    property OnGetSelectSQL: TGetSQLEvent
      read fGetSelectSQL write fGetSelectSQL;
    property OnGetCountSQL: TGetSQLEvent
      read fGetCountSQL write fGetCountSQL;
    property OnGetDataValue: TGetDataValueEvent
      read fGetDataValue write fGetDataValue;
    property OnAddResultSQL: TAddResultSQLEvent
      read fAddResultSQL write fAddResultSQL;
    property BeforeOpen: TDataSetNotifyEvent read fBeforeOpen write fBeforeOpen;
{$ifdef Delphi2009}
    property Encode: TdbcEncode read fEncode write fEncode default encDefault;
{$endif}
  end;

implementation

//The full source code is available on purchasing the product

end.
